package chapter03.item14;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @author zhaoyuqiang
 * @date 2021年09月30日 11:30
 * @description 实现Comparable实现
 */
public class People01 implements Comparable<People01>{

    private String name;
    private int age;

    public People01(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(People01 o) {
        if(this.age > o.getAge()){
            return 1;
        }else if(this.age < o.getAge()){
            return -1;
        }
        return 0;
    }

    @Override
    public String toString() {
        return "People01{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public static void main(String[] args) {

        People01 p1 = new People01("fei", 35);
        People01 p2 = new People01("qiang", 22);
        People01 p3 = new People01("sheng", 24);

        ArrayList<People01> list = new ArrayList<>();

        list.add(p1);
        list.add(p2);
        list.add(p3);

        //集合中对象类实现了Comparable接口
        //Collections.sort(list);

        //给集合传入Comparator接口的实现对象
        list.sort(new PeopleComparator());

        for(People01 p:list) {
            System.out.println(p);
        }

        System.out.println("---------------------------");

    }
}




class PeopleComparator implements Comparator<People01> {
    @Override
    public int compare(People01 o1, People01 o2) {
        if(o1.getAge() > o2.getAge()) {
            return 1;
        } else if (o1.getAge() < o2.getAge()) {
            return -1;
        }
        return 0;
    }
}




